﻿using System;
using System.Globalization;
using System.Windows.Controls;

namespace XamlTorrent.Common.Validation
{
    /// <summary>
    /// Validates a string to contain only characters used in hexadecimal representation.
    /// </summary>
    public class Base16ValidationRule : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            string str = (value ?? String.Empty).ToString();
            
            for (int i = 0; i < str.Length; i++)
            {
                char ch = str[i];

                if (!((ch >= 'A' && ch <= 'F') || (ch >= 'a' && ch <= 'f') || (ch >= '0' && ch <= '9')))
                    return new ValidationResult(false, 
                        String.Format("String contains illegal character '{0}' at position {1}.", ch, i)
                        );
            }

            return new ValidationResult(true, null);
        }
    }
}
